//
//  AddBankCardVC.m
//  Zhiche-Carriage
//
//  Created by LeeBruce on 16/7/16.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "AddBankCardVC.h"
#import "TopBackView.h"
#import "WKProgressHUD.h"
#import "Common.h"
#import "GYBankCardFormatTextField.h"

@interface AddBankCardVC ()<UITextFieldDelegate>

@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic,strong) UITextField *nameTextField;//持卡人
@property (nonatomic,strong) GYBankCardFormatTextField *bankcardTextField;//卡号
@property (nonatomic,strong) UITextField *phoneNumberTextField;//卡类型
@property (nonatomic,strong) UITextField *bankStyleTextField;//手机号
@property (nonatomic,strong)  UIButton *captchaButton;
@property (nonatomic,copy) NSString *cardString;

@property (nonatomic,strong) NSMutableDictionary *postDic;

@property (nonatomic) NSInteger secondCountDown;

@end

@implementation AddBankCardVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.postDic = [NSMutableDictionary dictionary];
    TopBackView *topBackView= [[TopBackView alloc]initViewWithFrame:CGRectMake(0, 0, screenWidth, 64) andTitle:@"添加银行卡"];
    
    topBackView.rightButton.hidden = YES;
    [topBackView.leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:topBackView];
    
    [self initTextField];
    [self initSubViews];
}

-(void)initTextField
{
    
    self.nameTextField = [[UITextField alloc]init];
    self.bankcardTextField = [[GYBankCardFormatTextField alloc]init];
    self.bankStyleTextField = [[UITextField alloc]init];
    self.phoneNumberTextField = [[UITextField alloc]init];

    self.nameTextField.delegate = self;
    self.nameTextField.placeholder = @"请输入姓名";

    self.bankcardTextField.delegate = self;
    self.bankcardTextField.placeholder = @"请输入卡号";

    self.bankStyleTextField.delegate = self;
    self.bankStyleTextField.userInteractionEnabled = NO;

//    self.phoneNumberTextField.delegate = self;
//    self.phoneNumberTextField.placeholder = @"请输入银行预留手机号";

    
    self.bankcardTextField.keyboardType = UIKeyboardTypeNamePhonePad;
    self.phoneNumberTextField.keyboardType = UIKeyboardTypeNamePhonePad;

}


-(void) initSubViews
{
    
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, screenWidth, screenHeight)];
    self.scrollView.contentSize = CGSizeMake(screenWidth, screenHeight + 1);
    self.scrollView.backgroundColor = GrayColor;
    [self.view addSubview:self.scrollView];
    UIView *firstV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, cellHeight)];
    firstV.backgroundColor = WhiteColor;
    UILabel *firstL = [[UILabel alloc]initWithFrame:CGRectMake(18, 0, 300, cellHeight)];
    firstL.text = @"请绑定持卡人本人的银行卡";
    firstL.textColor = littleBlackColor;
    firstL.font = Font(14);
    [firstV addSubview:firstL];
    [self.scrollView addSubview:firstV];
    
    UIView *secondV = [self backViewWithFloatY:CGRectGetMaxY(firstV.frame) andString:@"持卡人" andField:self.nameTextField andColor:littleBlackColor];
    
    [self.scrollView addSubview:secondV];
    
    UIView *thirdV = [self backViewWithFloatY:CGRectGetMaxY(secondV.frame) andString:@"卡号" andField:self.bankcardTextField andColor:littleBlackColor];
    
    [self.scrollView addSubview:thirdV];
    
    UIView *fourthV = [self backViewWithFloatY:CGRectGetMaxY(thirdV.frame) andString:@"卡类型" andField:self.bankStyleTextField andColor:littleBlackColor];
    
    [self.scrollView addSubview:fourthV];
    
    //手机号
//    UIView *fifthV = [self backViewWithFloatY:CGRectGetMaxY(fourthV.frame) andString:@"手机号" andField:self.phoneNumberTextField andColor:littleBlackColor];
    
//    [self.scrollView addSubview:fifthV];

    /*
    UIView *sixV = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(fifthV.frame), screenWidth, cellHeight)];
    sixV.backgroundColor = WhiteColor;
    [self.scrollView addSubview:sixV];
    
    UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(0,0, screenWidth, 0.5)];
    [sixV addSubview:label1];
    label1.backgroundColor = LineGrayColor;
    
    //获取验证吗
    self.captchaButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    _captchaButton.frame = CGRectMake(screenWidth - 90 * kWidth, (cellHeight - 23)/2.0, 75 * kWidth, 23 * kHeight);
    [_captchaButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [_captchaButton setTitleColor:YellowColor forState:UIControlStateNormal];
    _captchaButton.backgroundColor = Color_RGB(253, 243, 232, 1);
    [_captchaButton addTarget:self action:@selector(captchaButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    _captchaButton.titleLabel.font = Font(12);
    _captchaButton.layer.cornerRadius = 5;
    _captchaButton.layer.borderColor = YellowColor.CGColor;
    _captchaButton.layer.borderWidth = 0.5;
    
    [sixV addSubview:_captchaButton];
    */
    [self initBottomView];
    
}

-(void)initBottomView
{
    /*
    UILabel *messageL = [[UILabel alloc]initWithFrame:CGRectMake(18, 5 * cellHeight + 30, screenWidth - 38, 60)];
    messageL.numberOfLines = 0;
    messageL.textColor = Color_RGB(156, 156, 156, 1);
    messageL.font = Font(11);
    messageL.tag = 200;
    NSString *string = [NSString stringWithFormat:@"%@",self.phoneNumberTextField];
    string = [string stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
    
//    messageL.text = [NSString stringWithFormat:@"绑定银行卡需要短信确认，验证码已发送至手机%@,请按提示操作",string];
    [self.scrollView addSubview:messageL];
    */
    UIButton *addButton = [UIButton buttonWithType:UIButtonTypeCustom];
    addButton.frame = CGRectMake(18, 5 * cellHeight + 30, screenWidth - 36, Button_height);
    [addButton setTitle:@"添加银行卡" forState:UIControlStateNormal];
    addButton.backgroundColor = YellowColor;
    addButton.layer.cornerRadius = 5;
    [addButton setTitleColor:WhiteColor forState:UIControlStateNormal];
    [addButton addTarget:self action:@selector(addButton) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:addButton];
    
}

-(void)addButton
{
    NSLog(@"%@",self.pwdString);
    
    [self.postDic setObject:self.pwdString forKey:@"cashPwd"];
    
    if ([[self.postDic allKeys] count] != 3) {
        [WKProgressHUD popMessage:@"请将信息补充完整" inView:self.view duration:1.5 animated:YES];

    } else {
        
        NSLog(@"%@",self.postDic);
        Common *c = [[Common alloc]init];
        [c afPostRequestWithUrlString:bind_bankcard parms:self.postDic finishedBlock:^(id responseObj) {
            

            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
            
            
            [WKProgressHUD popMessage:dic[@"message"] inView:self.view duration:1.5 animated:YES];
            
            //延迟执行
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self.navigationController popViewControllerAnimated:YES];
                
            });

            

            
        } failedBlock:^(NSString *errorMsg) {
            NSLog(@"%@",errorMsg);
        }];
        
    }
    
    
}


-(UIView *)backViewWithFloatY:(CGFloat)y andString:(NSString *)string andField:(UITextField *)field andColor:(UIColor *)color
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, y, screenWidth, cellHeight)];
    UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(0,0, screenWidth, 0.5)];
    [view addSubview:label1];
    label1.backgroundColor = LineGrayColor;
    
    
    UILabel *titleL = [[UILabel alloc]initWithFrame:CGRectMake(18, 0.5, 100, cellHeight)];
    titleL.text = string;
    titleL.font = Font(13);
    titleL.textColor = fontGrayColor;
    [view addSubview:titleL];
    
    field.frame = CGRectMake(screenWidth - 250 - 18, 1, 250, cellHeight);
    [view addSubview:field];
    view.backgroundColor = WhiteColor;
    field.textAlignment = NSTextAlignmentRight;
    field.textColor = littleBlackColor;
    field.font = Font(13);
    
    return view;
    
    
    //    dispatch_async(dispatch_get_global_queue(0, 0), ^{
    //        // 处理耗时操作的代码块...
    //
    //        //通知主线程刷新
    //        dispatch_async(dispatch_get_main_queue(), ^{
    //            //回调或者说是通知主线程刷新，
    //        });
    //
    //    });

}

/*

-(void)captchaButtonAction:(UIButton *)sender
{
    //先判断手机号的正确
    NSString *regExp = @"^[1]([3][0-9]|[8][0-9]|[5][0-9]|45|47|76|77|78)[0-9]{8}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regExp];
    BOOL isRight = [pred evaluateWithObject:self.phoneNumberTextField.text];
    
    if (isRight) {
        
        
        NSString *urlString = [NSString stringWithFormat:@"%@login/captcha",Main_interface];
        NSDictionary *dic = @{@"phone":self.phoneNumberTextField.text,
                              @"usertype":userType};
        
        
        Common *c = [[Common alloc]init];
        
        [ c afPostRequestWithUrlString:urlString parms:dic finishedBlock:^(id responseObj) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
            
            [WKProgressHUD popMessage:dict[@"message"] inView:self.view duration:1.5 animated:YES];

            if ([dict[@"success"] boolValue]) {
                
                [sender setTintColor:WhiteColor];
                sender.userInteractionEnabled = NO;
                _secondCountDown = 60;
                NSTimer *time = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireAction:) userInfo:nil repeats:YES];
                [time fire];

                
                UILabel *label = [self.view viewWithTag:200];
                
                NSString *string = [NSString stringWithFormat:@"%@",self.phoneNumberTextField];
                string = [string stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];

                label.text = [NSString stringWithFormat:@"绑定银行卡需要短信确认，验证码已发送至手机%@,请按提示操作",string];

                
                
            }
            
        } failedBlock:^(NSString *errorMsg) {
            
            NSLog(@"%@",errorMsg);
            
        }];
        
        
    } else {
        
        [WKProgressHUD popMessage:@"手机号码不正确，请重新输入" inView:self.view duration:1.5 animated:YES];
        
    }

}

-(void)timeFireAction:(NSTimer *)time
{

_secondCountDown --;

//设置button下划线
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"(%lds)",_secondCountDown]];
NSRange strRange = {0,[str length]};
[str addAttribute:NSForegroundColorAttributeName value:YellowColor range:strRange];  //设置颜色
[self.captchaButton setAttributedTitle:str forState:UIControlStateNormal];


if (_secondCountDown <= 0) {
    [time invalidate];
    self.captchaButton.userInteractionEnabled = YES;
    //设置button下划线
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"获取验证码"];
    NSRange strRange = {0,[str length]};
    [str addAttribute:NSForegroundColorAttributeName value:YellowColor range:strRange];  //设置颜色
    //        [str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:strRange];
    
    [self.captchaButton setAttributedTitle:str forState:UIControlStateNormal];
    
 }
}
*/


-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == self.bankcardTextField) {
        
        [self.bankcardTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

    }
}


-(void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField == self.bankcardTextField) {
        

    }
    
    if (textField == self.nameTextField) {
        [self.postDic setObject:self.nameTextField.text forKey:@"userName"];
    }
    
    if (textField == self.phoneNumberTextField) {
//        [self.postDic setObject:self.phoneNumberTextField.text forKey:@"phone"];
    }
    
}

-(void)textFieldDidChange:(UITextField *)textField
{
    
    NSLog(@"%@",textField.text);
    
    NSString *string = textField.text;
    string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
    self.cardString = string;

    if (string.length >= 16) {
        
        [self checkBankCardWithString:string];
   
    }
}

//检测银行卡
-(void)checkBankCardWithString:(NSString *)string

{
    Common *c = [[Common alloc]init];
    [c afPostRequestWithUrlString:check_bankcard parms:@{@"card":string} finishedBlock:^(id responseObj) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
        

        if ([dic[@"success"] boolValue]) {
            self.bankStyleTextField.text = dic[@"data"][@"bankname"];
            
            [self.postDic setObject:string forKey:@"bankCard"];
            
        } else {
            
            
//            [WKProgressHUD popMessage:dic[@"message"] inView:self.view duration:1.5 animated:YES];

        }
        
    } failedBlock:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
}


//点击屏幕空白处去掉键盘
//- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
//{
//        [self.phoneNumberTextField resignFirstResponder];
////        [self.textSummary resignFirstResponder];
//    
//}




//点击return 按钮 去掉
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}


-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
